package at.ac.tuwien.lsds.csv;

import java.io.*;
import java.util.List;
import java.util.Properties;

import org.apache.log4j.Logger;
import org.hamcrest.core.IsInstanceOf;

import at.ac.tuwien.lsds.Main;
import at.ac.tuwien.lsds.model.Application;
import at.ac.tuwien.lsds.util.ApplicationOutputFile;
import at.ac.tuwien.lsds.util.OutputFile;
import at.ac.tuwien.lsds.util.ProcessSummaryOutputFile;
import at.ac.tuwien.lsds.util.Settings;

public class WriterImpl implements Writer {
	private FileWriter fw;
	private BufferedWriter out;
	private static final Logger log = Logger.getLogger(WriterImpl.class);


	@Override
	public void writeToCSV(OutputFile outputFile) throws IOException {
		try {
		File f = new File(outputFile.getFilePath());
		
//		log.debug("File: "+outputFile.getFilePath());
//		log.debug("File exists: "+f.exists());
//		log.debug("IsProcessSummaryOutputFile: "+ProcessSummaryOutputFile.class.isInstance(outputFile));
		
		if(f.exists() && ProcessSummaryOutputFile.class.isInstance(outputFile) ) {
			this.fw = new FileWriter(f, true);
			out = new BufferedWriter(fw);
			log.info("EXTENDED: "+outputFile.getFilePath());
		} else {
			this.fw = new FileWriter(outputFile.getFilePath());
			out = new BufferedWriter(fw);
			log.info("CREATED: "+outputFile.getFilePath());
			out.write(outputFile.getHeadline());
			out.newLine();
		}
		
		for (String row : outputFile.getContentRows()) {
			out.write(row);
			out.newLine();
		}

		out.close();
		} catch(IOException e) {
			e.printStackTrace();
		}
		
	}

}
